import React, { useEffect, useRef, useState } from "react";
import axios from "../../utils/http"
import { Popup } from 'antd-mobile'
import { formatTimestamp } from "../utils/fun"

const PopShow = React.memo((props) => {
    const { items, commentCount, commentList, showIconPosition, setPink, addComment } = props
    const { _id } = JSON.parse(localStorage.getItem("user"))[0] || ""
    

    const Inp = useRef()
    const [inputValue, setInputVal] = useState("") // 存储评论信息
    const [placeValue, setPlaceValue] = useState("善于结善缘，恶言伤人心") // 改变placeholder
    const [selectVal, setSelectVal] = useState(1) // 判断调用方法
    const [itemObj, setItemObj] = useState([]) // 临时存储父级评论信息
    const [childObj, setChildObj] = useState([]) // 临时存储子级评论信息
    const [loadingChildComments, setLoadingChildComments] = useState(false);
    const [childComments, setChildComments] = useState({}); // 存储每个父评论的子评论
    // 用一个对象来保存每个父评论的展开状态
    const [expandedComments, setExpandedComments] = useState({});
    // 管理每个父评论的分页状态
    const [pageState, setPageState] = useState({});
    const childRenRefs = useRef({}) // 用来存储每个子评论的ref

    // 添加子级评论
    const addCommentChild = async (parent_comment_id, parent_id) => {
        const obj = {
            userId: _id, // 用户id
            videoId: items._id, // 视频id
            content: inputValue, // 内容
            parent_comment_id: parent_comment_id, // 父级ID
            created_at: Date.now(), // 评论时间
            parent_id: parent_id // 是否给某个子级评论
        }
        const data = await axios.post("/yzh/CommentChildAdd", obj)
        if (data.code == 200) {
            setInputVal("")
        } else {
            console.log("错误了");
        }
    }

    // 输入框判断
    const submitComment = () => {
        if (selectVal === 1) {
            addComment(inputValue)
        } else if (selectVal === 2) {
            addCommentChild(itemObj._id, null)
            setItemObj({})
            setSelectVal(1)
        } else {
            addCommentChild(itemObj._id, childObj._id)
            setItemObj([])
            setChildObj([])
            setSelectVal(1)
        }
        setPlaceValue("善于结善缘，恶言伤人心")
        setInputVal("")
    }
    // 加载多个父评论的子评论
    const loadChildComments = async (parentCommentIds) => {
        setLoadingChildComments(true);

        // 发起请求，加载多个父评论的子评论
        try {
            const data = await axios.post("/yzh/getChildComments", { parentCommentIds: parentCommentIds, page: 1, pageSize: 3 })
            setChildComments(prev => ({
                ...prev,
                ...data.childComments
            }));
            // console.log(data);
            setLoadingChildComments(false);
            // 如果返回的数据没有更多评论，则不显示“加载更多”按钮
            setPageState((prevState) => ({
                ...prevState,
                [parentCommentIds]: {
                    ...prevState[parentCommentIds],
                    hasMore: data.hasMore, // 是否有更多子评论
                }
            }))

        } catch (e) {
            console.log(e);
            setLoadingChildComments(false);
        }
    };
    // 更新每个父评论的分页状态
    const loadMoreChildComments = async (commentId) => {
        const currentPage = pageState[commentId] ?.currentPage || 1;
        const nextPage = currentPage + 1;

        setPageState((prevState) => ({
            ...prevState,
            [commentId]: {
                ...prevState[commentId],
                currentPage: nextPage,
            },
        }));

        try {
            const data = await axios.post("/yzh/getChildComments", {
                parentCommentIds: commentId, // 只加载当前评论的子评论
                page: nextPage,
                pageSize: 3,
            });
            setChildComments((prev) => ({
                ...prev,
                [commentId]: [
                    ...(prev[commentId] || []), // 保留已经加载的子评论
                    ...data.childComments[commentId],
                ],
            }));

            // 如果返回的数据没有更多评论，则不显示“加载更多”按钮
            setPageState((prevState) => ({
                ...prevState,
                [commentId]: {
                    ...prevState[commentId],
                    hasMore: data.hasMore, // 是否有更多子评论
                }
            }))
        } catch (e) {
            console.log(e);
        }
    };
    // 切换子评论展开/收起状态
    const toggleExpand = (commentId) => {
        setExpandedComments(prevState => ({
            ...prevState,
            [commentId]: !prevState[commentId], // 切换当前评论的展开状态
        }));
        setPageState((prevState) => ({
            ...prevState,
            [commentId]: {
                ...prevState[commentId],
                currentPage: 1, // 初始化第一页
                hasMore: true, // 初始状态有更多子评论
            },
        }));
    };

    // 获取当前页面需要加载的父评论ID
    const parentCommentIdsToLoad = commentList.filter(comment => !childComments[comment._id]).map(comment => comment._id);

    useEffect(() => {
        if (parentCommentIdsToLoad.length > 0 && loadingChildComments) {
            loadChildComments(parentCommentIdsToLoad);
        }
    }, [childComments, loadingChildComments]);

    // 平滑展示评论并计算高度
    const addExpanded = (id) => {
        // 如果没有展开，获取内容的高度并展开
        const obj = childRenRefs.current[id]

        if (obj) {
            setTimeout(() => {
                obj.style.maxHeight = `${obj.scrollHeight}px`;
            }, 0)
            setTimeout(() => {
                obj.classList.add('expanded');
                obj.style.maxHeight = 'none'; // 展开后不限制高度
            }, 300); // 等待过渡结束后设置最大高度为auto
        }
    }

    // 平滑移除评论并计算高度
    const removeExpanded = (id) => {
        const obj = childRenRefs.current[id]

        if (obj) {
            // 如果已经展开，收缩评论框
            obj.style.maxHeight = `${obj.scrollHeight}px`;
            setTimeout(() => {
                obj.classList.remove('expanded');
                obj.style.maxHeight = '0px'; // 恢复到初始的最大高度
            }, 300); // 等待过渡结束后再设置固定高度
            setTimeout(() => {
                toggleExpand(id)
            }, 350)
        }
    }

    return <>
        <Popup
            visible={showIconPosition}
            onMaskClick={() => {
                setPink(false)
            }}
            onClose={() => {
                setPink(false)
            }}
            showCloseButton
            bodyStyle={{
                borderTopLeftRadius: '8px',
                borderTopRightRadius: '8px',
                minHeight: '60vh',
            }}
        >
            <div id="pupShow">
                <div className="tit">
                    <span>{commentCount} </span>条评论
                </div>
                <div className="context">
                    {
                        commentList.length > 0 ?
                            commentList.map(item => {
                                return <div className="text" key={item._id}>
                                    <div className="img">
                                        <img src={item.userId.imgUrl} alt="嘿嘿嘿" />
                                    </div>
                                    <div className="cont">
                                        <p className="pp1">{item.userId.username}</p>
                                        <p className="pp2">{item.content}</p>
                                        <p className="pp3">
                                            <span className="sp1">{formatTimestamp(item.created_at)}</span>
                                            <span
                                                className="sp2"
                                                onClick={() => {
                                                    setItemObj(item)
                                                    setSelectVal(2)
                                                    setPlaceValue(`回复@${item.userId.username}`)
                                                    Inp.current.focus()
                                                }}>回复</span>
                                            <span className="sp3">{item.like_count} 赞</span>
                                        </p>
                                        <div className="childRen" ref={(el) => (childRenRefs.current[item._id] = el)}>
                                            {childComments[item._id] && (
                                                <>
                                                    {expandedComments[item._id] && (
                                                        <>
                                                            {childComments[item._id].map(child => (
                                                                <div key={child._id} className="childCont">
                                                                    <div className="img">
                                                                        <img src={child.userId.imgUrl} alt="嘿嘿嘿" />
                                                                    </div>
                                                                    <div className="cont">
                                                                        {
                                                                            child.parent_id === null ?
                                                                                <p className="pp1">{child.userId.username}</p>
                                                                                :
                                                                                <p className="pp1">
                                                                                    {child.userId.username}
                                                                                    <span>  回复  </span>
                                                                                    {child.replyToCommentData.userId.username}
                                                                                </p>
                                                                        }
                                                                        <p className="pp2">{child.content}</p>
                                                                        <p className="pp3">
                                                                            <span className="sp1">{formatTimestamp(child.created_at)}</span>
                                                                            <span
                                                                                className="sp2"
                                                                                onClick={() => {
                                                                                    setItemObj(item)
                                                                                    setChildObj(child)
                                                                                    setSelectVal(3)
                                                                                    setPlaceValue(`回复@${item.userId.username}`)
                                                                                    Inp.current.focus()
                                                                                }}>回复</span>
                                                                            <span className="sp3">{child.like_count} 赞</span>
                                                                        </p>
                                                                    </div>
                                                                </div>
                                                            ))}
                                                        </>
                                                    )}
                                                </>
                                            )}
                                        </div>
                                        <p className="pp4">
                                            {/* {
                                            childComments[item._id] && */}
                                            <span className="lp1">——</span>
                                            {/* } */}
                                            {
                                                expandedComments[item._id] ?
                                                    <>
                                                        {
                                                            pageState[item._id] ?.hasMore && (
                                                                <span
                                                                    className="lp2"
                                                                    onClick={() => {
                                                                        loadMoreChildComments(item._id)
                                                                        addExpanded(item._id)
                                                                    }}
                                                                >展开更多</span>
                                                            )
                                                    }
                                                        <span
                                                            className="lp2"
                                                            onClick={() => {
                                                                removeExpanded(item._id)
                                                            }}
                                                        >收起</span>
                                                    </>
                                                    :
                                                    // childComments[item._id] &&
                                                    <span
                                                        className="lp2"
                                                        onClick={() => {
                                                            loadChildComments(item._id)
                                                            toggleExpand(item._id)
                                                            addExpanded(item._id)
                                                        }}
                                                    >展开</span>
                                            }
                                        </p>
                                    </div>
                                </div>
                            })
                            :
                            <p className="pops">快来评论吧~</p>
                    }
                </div>
                <div className="boTT">
                    <input type="text" ref={Inp} className="comment-input" placeholder={placeValue} value={inputValue} onInput={(e) => { setInputVal(e.target.value) }} />
                    <span onClick={() => submitComment()}>发表</span>
                </div>
            </div>
        </Popup >
    </>
})

export default PopShow